package com.example.springboot.controller;

import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.common.Result;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

import com.example.springboot.service.INoteService;
import com.example.springboot.entity.Note;

import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/note")
    public class NoteController {
    
    @Resource
    private INoteService noteService;

    //插入笔记
    @PostMapping("/insert")
    public Result insert(@RequestBody Note note) {
        note.setUserId(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId());
        note.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return noteService.insert(note);
    }

    //更新笔记
    @PostMapping("/update")
    public Result update(@RequestBody Note note) {
        note.setUserId(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId());
        note.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return noteService.saveNote(note);
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        if (noteService.removeById(id))
            return Result.success();
        return Result.error();
    }

    //根据id批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(noteService.removeByIds(ids));
    }

    //查找所有
    @GetMapping
    public Result findAll() {
        return Result.success(noteService.list());
    }

    //根据id查找
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(noteService.getById(id));
    }

    //根据引导id查找
    @GetMapping("/guide")
    public Result findByGuide(@RequestParam Integer guideId){
        return noteService.findByGuide(guideId);
    }

    //根据用户id和搜索的引导内容批量查找
    @GetMapping("/searchByGuide")
    public Result searchByGuide(@RequestParam String guideName) {
        return noteService.searchByGuide(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId(),guideName);
    }

    //根据用户id和引导id批量查找
    @GetMapping("/getByUidAndGid")
    public Result getByUidAndGid(@RequestParam Integer guideId) {
        return noteService.getByUidAndGid(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId(),guideId);
    }
}

